<?php


namespace addon\store\store\controller;

use addon\store\model\StoreGoods as StoreGoodsModel;
use addon\store\model\StoreGoodsSku as StoreGoodsSkuModel;

/**
 * 实物商品
 * Class Goods
 * @package app\shop\controller
 */
class Goods extends BaseStore
{

    public function __construct()
    {
        //执行父类构造函数
        parent::__construct();
    }

    /**
     * 商品列表
     * @return mixed
     */
    public function index()
    {
        if (request()->isAjax()) {
            $page_index = input('page', 1);
            $page_size  = input('page_size', PAGE_LIST_ROWS);

            $condition   = [
                ['g.is_delete', '=', 0],
                ['g.site_id', '=', $this->site_id],

            ];
            $search_text = input('search_text', "");
            if (!empty($search_text)) {
                $condition[] = ['g.goods_name', 'like', '%' . $search_text . '%'];
            }

            $start_sale = input('start_sale', 0);
            $end_sale   = input('end_sale', 0);
            if (!empty($start_sale)) $condition[] = ['sg.store_sale_num', '>=', $start_sale];
            if (!empty($end_sale)) $condition[] = ['sg.store_sale_num', '<=', $end_sale];
            $store_goods_model = new StoreGoodsModel();
            $res               = $store_goods_model->getGoodsPageList($condition, $page_index, $page_size, $this->store_id);
            return $res;
        } else {

            return $this->fetch("goods/lists", [], $this->replace);
        }
    }

    /**
     * 更新门店的库存
     */
    public function saveStock()
    {
        $stocks                = input('stock', []);
        $sku_ids               = input('sku_id', []);
        $goods_ids             = input('goods_id', []);
        $store_goods_sku_array = [];
        foreach ($stocks as $key => $stock) {
            $store_goods_sku_array[] = [
                'store_stock' => $stock,
                'store_id'    => $this->store_id,
                'sku_id'      => $sku_ids[$key],
                'goods_id'    => $goods_ids[$key]
            ];
        }
        $store_goods_sku_model = new StoreGoodsSkuModel();
        $res                   = $store_goods_sku_model->editStock($store_goods_sku_array);

        return $res;
    }

    /**
     * 获取SKU商品列表
     * @return array
     */
    public function getGoodsSkuList()
    {
        if (request()->isAjax()) {
            $goods_id              = input("goods_id", 0);
            $store_goods_sku_model = new StoreGoodsSkuModel();
            $res                   = $store_goods_sku_model->getGoodsSkuList([['gs.goods_id', '=', $goods_id], ['gs.site_id', '=', $this->site_id]], $this->store_id);
            return $res;
        }
    }
}